using System;

namespace ClassicBehaviorTree
{
    public class Selector : Container
    {
        public override NodeState Update()
        {
            for (int i = _successCounter; i < _subNodes.Count; i++)
            {
                switch (_subNodes[i].Update())//the first success node
                {
                    case NodeState.Ready:
                        _successCounter = i + 1;
                        _state = NodeState.Ready;
                        break;
                    case NodeState.Success:
                        _successCounter = 0;
                        _state = NodeState.Success;
                        return _state;
                    case NodeState.Failure:
                        _successCounter = i + 1;
                        if (_successCounter == _subNodes.Count)
                        {
                            _successCounter = 0;
                            _state = NodeState.Failure;
                            return _state;
                        }
                        break;
                    case NodeState.Abort:
                        _successCounter = 0;
                        _state = NodeState.Abort;
                        return _state;
                    default:
                        throw new Exception("This should never happen, but clearly it has.");
                }
            }
            return _state;
        }
    }
}
